import time
from PIL import Image
from io import BytesIO
from ddddocr import DdddOcr
from selenium.webdriver.common.by import By
from taobao_check.tools import click_by_js, pil2bytes
from .base import BaseBrush


class TaoMeng(BaseBrush):
    login_url = "https://taom-merchant.zhaojinmiao.com/login"
    index_url = "https://taom-merchant.zhaojinmiao.com/home/index"
    check_url = "https://taom-merchant.zhaojinmiao.com/task/taskGroup?m2=2&m1=0&tab=2"

    def __init__(self, config, tab):
        super().__init__("淘盟", "taomeng", config, tab)
        self.ocr = DdddOcr()

    def login(self):
        while True:
            if self.browser.current_url != self.login_url:
                self.browser.get(self.login_url)

            input_css = "div.login-form>form>div>div>div>input"
            text_input, pwd_input, _ = self.find_elements((By.CSS_SELECTOR, input_css))

            self.enter_text(text_input, self.username)
            self.enter_text(pwd_input, self.password)
            # 新窗口打开验证码
            self.browser.execute_script("window.open('https://api-merchant.zhaojinmiao.com/Login/verify.html')")
            handles = self.browser.window_handles
            self.browser.switch_to.window(handles[1])
            # 对网页截图并裁剪
            element = self.find_element((By.CSS_SELECTOR, "body>img"))
            location = element.location
            size = element.size
            width = location['x'] + size['width']
            height = location['y'] + size['height']
            img_data = self.browser.get_screenshot_as_png()
            im = Image.open(BytesIO(img_data))
            im = im.crop((int(location['x']), int(location['y']), int(width), int(height)))
            code = self.ocr.classification(pil2bytes(im))
            # 关闭验证码窗口，切换到登录窗口
            self.browser.close()
            self.browser.switch_to.window(handles[0])
            # 尝试登录
            _, _, verifi_input = self.find_elements((By.CSS_SELECTOR, input_css))
            self.enter_text(verifi_input, code)
            self.click_button((By.CSS_SELECTOR, 'div.login-form>form>div>div>button'))

            if self.wait_login(3):
                break

    def check_user(self):
        # 等待页面加载
        self.print_log("taomeng check...", debug=True)
        time.sleep(1.5)     # 等待页面加载
        wait_check = self.find_elements((By.CSS_SELECTOR, "div.sub-cond>div"))[2]
        text = wait_check.get_attribute('textContent').strip()
        if text == "待验号(0)":
            self.print_log("没有买号.", debug=True)
            self.sleep(self.refresh_time)
            return False

        self.print_log("发现待验买号.")
        click_by_js(self.browser, wait_check)
        self.click_button((By.CSS_SELECTOR, "button[type='button'].kong-yellow"))
        selector = (By.CSS_SELECTOR, "div.ivu-modal-body>div>div>span.mr10")
        username = self.find_element(selector).get_attribute('textContent').strip()
        self.print_log(f"当前待验买号为：【{username}】")
        start = time.time()
        result = self.check.check_user(username, self.print_log)
        self.print_log(f"验号结果为: {'通过' if result else '不通过'}. 用时: {time.time() - start:.2f}s")

        if result:
            start_button = self.find_button((By.CSS_SELECTOR, "div.ivu-modal-body>div>div>button[type='button'].blue"))
            click_by_js(self.browser, start_button)
            self.print_log("开始任务.\n")
        else:
            rematch_button = self.find_button((By.CSS_SELECTOR, "div.ivu-modal-body>div>div>button[type='button'].yellow"))
            click_by_js(self.browser, rematch_button)
            self.print_log("开始重新匹配买号.\n")

        self.sleep(2)
        return True
